package com.gxljc.bear.crawler.image;

import com.gxljc.commons.util.Pair;
import com.gxljc.bear.crawler.base.DolphinCrawlerConsts;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.Map;

/**
 * 图片更新。
 *
 * @author tanghaitao
 * @since 2022-9-6
 */
public class ImageFresh {
    public static Logger LOG = Logger.getLogger(ImageFresh.class);
    private static final ImageFresh instance = new ImageFresh();

    private ImageFresh() {
    }

    public static ImageFresh getInstance() {
        return instance;
    }


    //刷新对象
    //return Pair
    //       first : 1,0
    //       second: url
    public Pair<Integer, String> freshOne(String pic) throws Exception {
        return freshOne(pic, null);
    }

    //刷新对象
    //return Pair
    //       first : 1,0
    //       second: url
    public Pair<Integer, String> freshOne(String pic, Map<String, String> property) throws Exception {
        int type = DolphinCrawlerConsts.RESULT_YES;
        if (StringUtils.isEmpty(pic))
            return new Pair<Integer, String>(type, pic);
        Map<String, Object> newPicMap = saveImage(pic, property);
        String newPic = null;
        if (newPicMap == null || newPicMap.isEmpty()) {
            type = DolphinCrawlerConsts.RESULT_NO;
            newPic = pic;
        } else {
            newPic = (String) newPicMap.get(ImageConsts.IMAGE_MAP_NAME.URL.getValue());
        }
        return new Pair<Integer, String>(type, newPic);
    }

//    //缓存封面图片
//    private int freshLogoUrl(MtimeTable table) throws Exception {
//        String pic = table.logo_url;
//        if (StringUtils.isEmpty(pic)) return DolphinCrawlerConsts.RESULT_YES;
//        Pair<Integer, String> newPicPair = freshOne(pic);
//        table.setLogo_url(newPicPair.second);
//        return newPicPair.first;
//    }


    //缓存图片
    private Map<String, Object> saveImage(String pic) throws Exception {
        return saveImage(pic, null);
    }

    //缓存图片
    private Map<String, Object> saveImage(String pic, Map<String, String> property) throws Exception {
        if (StringUtils.isEmpty(pic)) return null;
        RefreshImage ri = RefreshImage.getInstance();
        Map<String, Object> newPicMap = ri.saveOriginalImageUrl(pic, property);
        if (newPicMap == null || newPicMap.isEmpty())
            return null;
        return newPicMap;
    }
}
